package com.easyim.imserver.config;

import com.easyim.imserver.handler.message.Handler;
import io.netty.channel.Channel;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Configuration
public class ChannelConfig implements ApplicationContextAware {

    private ApplicationContext applicationContext;
    @Bean("channelMap")
    public Map<String, Map<String, Channel>> channelMap(){
        Map<String, Map<String, Channel>> localSession = new ConcurrentHashMap<>();
        return localSession;
    }


    @Override
    public void setApplicationContext(ApplicationContext applicationContext)
            throws BeansException {
        this.applicationContext = applicationContext;
    }


    @Bean("msgHandler")
    public Map<String, Handler> msgHandler(){
        Map<String, Handler> handlerMap = applicationContext.getBeansOfType(Handler.class);
        //为啥要自己注入一个 为了方便给分发器使用
        Map<String, Handler> msgHandler =  new HashMap<>();
        handlerMap.forEach(
                (code, handler) -> {
                    msgHandler.put(handler.dealType(), handler);
                }
        );
        return msgHandler;
    }
}
